<script>
import {UploadImage} from "../api/img.js";

export default {
  props: {
    modelValue: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      saved: false,
      showPreview: false,
      image: ''
    }
  },
  computed: {
    localValue: {
      get() {
        return this.modelValue
      },
      set(val) {
        this.updateValue(val)
      },
    }
  },
  methods: {
    updateValue(val) {
      this.$emit('update:modelValue', val)
    },
    selectImage() {
      this.$refs.imageSelector.click()
    },
    onImageSelected(e) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        this.image = e.target.result
        this.showPreview = true
        const res = await UploadImage(e.target.result)
        if(res.status === 200){
          this.saved = true;
          this.updateValue(res.data.data)
          this.image = ''
        }
      }
      reader.readAsDataURL(e.target.files[0])
    }
  },
  watch: {
    localValue(val) {
      if(val) {
        this.showPreview = true
        this.saved = true
      }
    }
  },
}
</script>

<template>
  <div class="">
    <input type="file" hidden="" @change="onImageSelected" ref="imageSelector">
    <img @click="selectImage" v-if="showPreview" class="w-[100px] h-[100px] border object-cover" :src="localValue" :class="{'grayscale': !saved}" alt="avatar"/>
    <div @click="selectImage" v-if="!showPreview" class="w-[100px] h-[100px] border flex justify-center items-center">
      <fai icon="plus" class="text-gray-500"/>
    </div>
  </div>
</template>

<style scoped>

</style>